// 获取config文件夹下所有的组件
import BaseCompInfo from './base'
import { noLabelComps } from '@/views/view-editor/config/util';

const modules = import.meta.glob('./{biz,iview,layout,page}/*.ts', { eager: true, import: 'default' })

const allComponents: Record<string, string[]> = {}
const priority = ['iview', 'biz', 'layout', 'page']
const sortedPath = Object.keys(modules).sort((a, b) => {
  // 提取每个路径的目录名
  const dirA = a.split('/')[1]
  const dirB = b.split('/')[1]
  // 根据优先级进行比较
  return priority.indexOf(dirA) - priority.indexOf(dirB)
})

for (const path of sortedPath) {
  const names = path.match(/\.\/(\w+)\/([\w.]+)/)
  if (names) {
    const dirname = names[1]
    if (!allComponents[dirname]) {
      allComponents[dirname] = []
    }
    allComponents[dirname].push(modules[path] as any)
  }
}

const result: any[] = []

Object.keys(allComponents).forEach(key => {
  for (const item of allComponents[key]) {
    const compInstance = new BaseCompInfo(item as any)
    const comp = JSON.parse(JSON.stringify(compInstance.configInfo))

    if (key === 'page') {
      comp.configs.dataModel.list = []
    } else if (noLabelComps.includes(comp.drag.compName)) {
      // 无标题的组件删除表单校验配置
      const idx = comp.configs.dataModel.list.findIndex((i: any) => i.type === 'rule')
      if (idx > -1) {
        comp.configs.dataModel.list.splice(idx, 1)
      }
    }

    const keys = Object.keys(comp.configs)
    const data: Record<string, any> = {}

    for (const key of keys) {
      if (key !== 'watch' && !comp.configs[key].list.length) {
        delete comp.configs[key]
      } else {
        data[key] = {}
        
        comp.configs[key].list.forEach((item: any) => {
          data[key][item['model']] = item.defaultValue

          if (['CodeEditor', 'ColumnSetting', 'TabpaneSetting', 'TableColumnSetting'].includes(item.component)) {
            const label = item.label
            item.label = ''
            item.props = item.props || {}
            item.props.label = label
          }
        })

        // 配置Label属性
        comp.configs[key]['config'] = {
          labelPosition: ['events', 'slots'].includes(key) ? 'top' : 'left',
          labelWidth: ['events', 'slots'].includes(key) ? 120 : 90
        }
      }
    }
    comp.data = data
    result.push(comp)
  }
})

export default result